package vip.zhenzicheng.test.juc;

import java.util.concurrent.TimeUnit;

/**
 * volatile最佳实践
 *
 * @author zhenzicheng
 * @date 2022-09-05 15:24
 */
public class VolatileBastPractice {

}

/**
 * 状态标志
 */
class VolatileWithBoolean {

  private volatile static boolean flag = true;

  public static void main(String[] args) {
    new Thread(() -> {
      while (flag) {
        // do something...
      }
    }, "t1").start();

    try {
      TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    new Thread(() -> flag = false, "t2").start();
  }
}

/**
 * 读多写少场景
 */
class VolatileWithLock {

  private volatile int value;

  public int getValue() {
    return value; // 利用volatile保证读取操作的可见性
  }

  public synchronized int increment() {
    return value++; // 利用synchronized保证复合操作的原子性
  }
}
